package com.mjlf.t.heartinserct.server;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.concurrent.EventExecutorGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @ClassName HeartServerHandler
 * @auther mjlf
 * @Date 2019/9/18 11:34
 * @Description TODO
 */
public class HeartServerHandler extends ChannelInboundHandlerAdapter {

    //定义channel集合,管理channel,传入全局事件执行器
    public static ChannelGroup users = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){
            IdleStateEvent idleStateEvent = (IdleStateEvent)evt;
            String str = "";
            switch (idleStateEvent.state()){
                case READER_IDLE:
                    System.out.println("读超时");
                    break;
                case WRITER_IDLE:
                    System.out.println("写超时");
                    break;
                case ALL_IDLE:
                    //关闭通过
                    System.out.println(users.size());
                    ctx.channel().close();
                    System.out.println("全超时");
                    System.out.println();
                    System.out.println(users.size());
                    break;
            }
        }
    }

    /**
     * 当客户端连接服务端之后(打开连接)----->handlerAdded
     * 获取客户端的channel,并且放到ChannelGroup中去管理
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        users.add(ctx.channel());
        String asShortText = ctx.channel().id().asShortText();
        System.out.println("客户端添加，channelId为：" + asShortText);
    }

    //处理器移除时,移除channelGroup中的channel
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //打印移除的channel
        String asShortText = ctx.channel().id().asShortText();
        System.out.println("客户端被移除，channelId为：" + asShortText);
        users.remove(ctx.channel());
    }
}
